package examples;

import java.io.*;
import java.util.List;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import org.hibernate.Session;

import initDB.initH2.SessionFactoryUtils;
import initDB.initH2.entity.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@WebServlet(urlPatterns = "/helloJson")
public class HelloJson extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("application/json; charset=utf-8");
		PrintWriter pWriter = response.getWriter();

		JSONObject jsonObject = new JSONObject();
		
		Session session =SessionFactoryUtils.getSessionFactory().openSession();
		String query = "FROM User";
		List<User> list = session.createQuery(query).list();
		System.out.println("用户数据---------------------------");
		for (User user : list) {
			System.out.println(user.toString());
		}
		
		jsonObject.put("data", JSONArray.fromObject(list));
		String jsonstr = jsonObject.toString();

		pWriter.write(jsonstr);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	public static void main(String[] args) {
		System.out.println("hello world");
	}
}